package com.jinzhi.jzweb.utils;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class MyBlockingQueue<E> {

    int size;//阻塞队列最大容量

    ReentrantLock lock = new ReentrantLock();

    LinkedList<E> list=new LinkedList<>();//队列底层实现

    Condition notFull = lock.newCondition();//队列满时的等待条件
    Condition notEmpty = lock.newCondition();//队列空时的等待条件

    public MyBlockingQueue(int size) {
        this.size = size;
    }

    public Integer enqueue(E e,Integer i) throws InterruptedException {
        lock.lock();
        try {
            while (list.size() ==size)//队列已满,在notFull条件上等待
                notFull.await();
            list.add(e);//入队:加入链表末尾
           // System.out.println("入队：" +e);

            notEmpty.signal(); //通知在notEmpty条件上等待的线程
            return i;
        } finally {
            lock.unlock();
        }
    }

    public E dequeue() throws InterruptedException {

        new Thread(new Runnable() {
            @Override
            public void run() {
            }
        }).start();

        E e;
        lock.lock();
        try {
            while (list.size() == 0)//队列为空,在notEmpty条件上等待
                notEmpty.await();
            e = list.removeFirst();//出队:移除链表首元素
          //  System.out.println("出队："+e);

//            try {
//                throw new Exception("队列出现了错误");
//            } catch (Exception exception) {
//                exception.printStackTrace();
//            }

            notFull.signal();//通知在notFull条件上等待的线程
            return e;
        } finally {
            lock.unlock();
        }
    }
}
